package com.imooc.ad.index.interest;

import com.imooc.ad.index.IndexAware;
import com.imooc.ad.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;

/**
 * @ClassName UnitItIndex
 * Created by zghgchao 2019/3/27 16:07
 **/
@Slf4j
@Component
public class UnitItIndex implements IndexAware<String,Set<Long>> {

    // <itTag,adUnitId set>
    private static Map<String,Set<Long>> itUnitMap;

    // <adUnitId,itTag set>
    private static Map<Long,Set<String>> unitItMap;

    static {
        itUnitMap = new ConcurrentHashMap<>();
        unitItMap = new ConcurrentHashMap<>();
    }

    @Override
    public Set<Long> get(String key) {
        return itUnitMap.get(key);
    }

    @Override
    public void add(String key, Set<Long> value) {
        log.info("UnitItIndex  before add : {} ",itUnitMap);

        Set<Long> unitIds = CommonUtils.getorCreate(key, itUnitMap, ConcurrentSkipListSet::new);
        unitIds.addAll(value);

        for (Long unitId : value){
            Set<String> its = CommonUtils.getorCreate(unitId, unitItMap, ConcurrentSkipListSet::new);
            its.add(key);
        }
        log.info("UnitItIndex  after add : {} ",itUnitMap);
    }

    @Override
    public void update(String key, Set<Long> value) {
        log.error("interest index can not support update");
    }

    @Override
    public void delete(String key, Set<Long> value) {
        log.info("UnitItIndex  before delete : {} ",itUnitMap);
        Set<Long> unitIdSet = CommonUtils.getorCreate(key, itUnitMap, ConcurrentSkipListSet::new);
        unitIdSet.removeAll(value);

        for (Long unitId : value){
            Set<String> keywordSet = CommonUtils.getorCreate(unitId, unitItMap, ConcurrentSkipListSet::new);
            keywordSet.remove(key);
        }
        log.info("UnitItIndex  after delete : {} ",itUnitMap);
    }

    public boolean match(Long unitId, List<String> keywords){
        if (unitItMap.containsKey(unitId) && CollectionUtils.isNotEmpty(unitItMap.get(unitId))){
            Set<String> unitIts = unitItMap.get(unitId);
            // 判断 keywords是否是unitKeywords的子集
            return CollectionUtils.isSubCollection(keywords,unitIts);
        }
        return false;
    }
}
